

timeout=30
elapse=0
while test ${elapse} -lt ${timeout}
do
    if docker exec -t diss-db psql -h 127.0.0.1 -U diss -l > /dev/null 2>&1; then
        break
    fi
    elapse=$(($elapse+1))
    sleep 1
done



install_path="$1"
init_data_path="$install_path/datapack/init_data"

UserData=$(docker exec -t diss-db psql -h 127.0.0.1 -U diss -d diss -c "Select * from public.user" | grep "admin" | wc -l)
if [ $UserData -eq 1 ]; then
    echo " *** system user and role data check ok *** "
    return 1
else
   echo "init user and role data"
   echo "init data path: $init_data_path"
fi


for file in `ls $init_data_path`
do
    filepath=${install_path}/datapack/init_data/${file}
    if [[ "${filepath}" =~ .*.sql$ ]]; then
        if ! docker cp "${filepath}" diss-db:/opt; then
            echo "Unable to initialize ${file%.*}, copy initial data failed"
            return 1
        fi

        # docker exec -t diss-db psql -U diss -d diss -f "/opt/${file}" > tmp.txt
        # cat tmp.txt
        state=`docker exec -t diss-db psql -U diss -d diss -f "/opt/${file}" | grep COPY | awk -F' ' '{if($2==0) print "false"; else print "true"}'`
        if [ "${state}" != "true" ]; then
            echo "Unable to initialize ${file%.*}, process initial data failed"
            return 1
        fi
    fi
done
